package com.qmgyl.marketshop.distribute.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.qmfresh.service.common.dto.ListWithPage;
import com.qmfresh.service.entity.OrderDelivery;
import com.qmfresh.service.gateway.dto.DeliveryDetailQuery;
import com.qmgyl.marketshop.api.ServiceApi;
import com.qmgyl.marketshop.vo.DeliveryQuery;
import com.qmgyl.marketshop.vo.OrderDeliveryItemResult;
import com.qmgyl.marketshop.vo.OrderDeliveryVo;

import util.DateUtil;
import util.ExcelUtil_Extend;

@Controller
@RequestMapping(value = "/distribute")
public class DistributeController {
	@Autowired
	private ServiceApi serviceApi;

	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String order(@PathVariable("name") String name) {
		return "distribute/" + name;
	}

	/**
	 * 返回JSON数据
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "getList")
	public void getList(Integer page, Integer rows, Date start, Date end, Integer status, HttpServletResponse response)
			throws IOException {

		// 默认只查当天的配送单
		DeliveryQuery dq = new DeliveryQuery();
		dq.setPageSize(rows);
		dq.setPageIndex(page);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
		DateTime s = DateTime.parse(DateTime.now().toString("yyyy-MM-dd"), format);
		if (start != null) {
			s = DateTime.parse(new DateTime(start).toString("yyyy-MM-dd"), format);
		}
		dq.setStartDeliveryTime((int) (s.toDate().getTime() / 1000));
		if (end != null) {
			DateTime e = DateTime.parse(new DateTime(end).toString("yyyy-MM-dd"), format);
			dq.setEndDeliveryTime((int) (e.toDate().getTime() / 1000));
		}
		if (status != null && status != -1) {
			dq.setStatus(status);
		}

		ListWithPage<OrderDelivery> pages = serviceApi.orderDeliveryList(dq);

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", pages.getTotalCount());
		List<OrderDeliveryVo> ods = new ArrayList<>(pages.getListData().size());
		for (OrderDelivery od : pages.getListData()) {
			OrderDeliveryVo odv = new OrderDeliveryVo();
			odv.setAddress(od.getAddress());
			odv.setCompanyId(od.getCompanyId());
			odv.setCT(new Date((long) od.getCT() * 1000));
			odv.setUT(new Date((long) od.getUT() * 1000));
			odv.setDebtAmount(od.getDebtAmount());
			odv.setDelivererName(od.getDelivererName());
			odv.setId(od.getId());
			if (od.getShipTime() == 0) {
				odv.setShipTime(null);
			} else {
				odv.setShipTime(new Date((long) od.getShipTime() * 1000));
			}

			odv.setDelivererId(od.getDelivererId());
			odv.setDelivererPhone(od.getDelivererPhone());
			odv.setStartDeliveryTime(new Date((long) od.getStartDeliveryTime() * 1000));
			odv.setReceiveTotalAmount(od.getReceiveTotalAmount());
			odv.setReceiveTime(new Date((long) od.getReceiveTime() * 1000));
			odv.setPaidTotalAmount(od.getPaidTotalAmount());
			odv.setPaidTime(new Date((long) od.getPaidTime() * 1000));
			odv.setIsDeleted(od.getIsDeleted());
			odv.setIgnoreAmount(od.getIgnoreAmount());
			odv.setDriverDiscountAmount(od.getDriverDiscountAmount());
			odv.setDebtAmount(od.getDebtAmount());
			odv.setRefundAmount(od.getRefundAmount());
			odv.setName(od.getName());
			odv.setPhone(od.getPhone());
			odv.setStatus(od.getStatus());
			ods.add(odv);
		}
		data.put("rows", ods);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(data));
	}

	@RequestMapping(value = "detail")
	public String detail(Integer id, Integer companyId, Model model) {
		DeliveryDetailQuery ddq = new DeliveryDetailQuery();
		ddq.setCompanyId(companyId);
		ddq.setDeliveryId(id);
		List<OrderDeliveryItemResult> odirs = serviceApi.listDeliveryItem(ddq);
		// 计算总金额
		BigDecimal expectTotal = new BigDecimal(0);
		BigDecimal shipTotal = new BigDecimal(0);
		BigDecimal receiveTotal = new BigDecimal(0);
		for (OrderDeliveryItemResult odir : odirs) {
			expectTotal = expectTotal.add(odir.getExpectShipGoodsAmount());
			receiveTotal = receiveTotal.add(odir.getReceiveGoodsAmount());
			shipTotal = shipTotal.add(odir.getShipGoodsAmount());
		}
		expectTotal = expectTotal.setScale(2, RoundingMode.HALF_UP);
		receiveTotal = receiveTotal.setScale(2, RoundingMode.HALF_UP);
		shipTotal = shipTotal.setScale(2, RoundingMode.HALF_UP);
		model.addAttribute("itemList", odirs);
		model.addAttribute("expectTotal", expectTotal);
		model.addAttribute("receiveTotal", receiveTotal);
		model.addAttribute("shipTotal", shipTotal);
		return "distribute/detail";

	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(value = "export")
	@ResponseBody
	public String export(Integer status,Date start, Date end,HttpServletRequest request, HttpServletResponse response) throws Throwable {

		// 配送数据
		String fileName = "delivery_" + System.currentTimeMillis() + ".xls";
		DeliveryQuery query = new DeliveryQuery();
		if(start==null) {
			query.setStartDeliveryTime(DateUtil.getStartTimeStamp());
		}
		else {
			query.setStartDeliveryTime(DateUtil.getStartTimeStamp(start));
		}
		if(end == null) {
			query.setEndDeliveryTime(DateUtil.getEndTimeStamp());
		}
		else {
			query.setEndDeliveryTime(DateUtil.getEndTimeStamp(end));
		}
//		if (status != null && status != -1) {
//			query.setStatus(status);
//		}
		List<OrderDeliveryItemResult> odirs = serviceApi.listAllDeliveryItem(query);
		if(odirs.size()==0) {
			return "No Records";
		}
		/*
		 * List<String> headerList = ListUtils.newArrayList(); headerList.add("商户名称");
		 * headerList.add("序号"); headerList.add("商品名称"); headerList.add("商品规格");
		 * headerList.add("商品数量"); headerList.add("商户电话"); headerList.add("商户地址");
		 */
		List<List<String>> dataList = new ArrayList<>();
		int i = 0;
		long deliveryId=0;
		for (OrderDeliveryItemResult odir : odirs) {
			// 初始化数据集
			if(odir.getOrderDeliveryId()!=deliveryId) {
				i = 1;
				deliveryId = odir.getOrderDeliveryId();
			}
			else {
				i++;
			}
			List<String> rowList = new ArrayList<>();
			rowList.add(odir.getCompanyName());
			
			rowList.add(i + "");
			rowList.add(odir.getSkuName()+"("+odir.getSkuFormat() +")");
			rowList.add(odir.getSsuUnitPriceNum().toString());
			rowList.add(odir.getExpectGoodsNum().toString());
			rowList.add(odir.getCompanyPhone());
			rowList.add(odir.getCompanyName());

			dataList.add(rowList);

		}
		String[] head = { "商户名称", "序号", "商品名称", "商品规格", "商品数量", "商户电话", "商户地址" };
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("配送单");
		sheet.setColumnWidth(0, 8000);
		sheet.setColumnWidth(2, 8000);
		sheet.setColumnWidth(6, 18000);
		ExcelUtil_Extend.createExcelMerge(workbook, sheet, "配送单", head, dataList, false, null, null, null, null);

		ExcelUtil_Extend.mergedRegion(sheet, 0, 1, sheet.getLastRowNum(), workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 5, 1, sheet.getLastRowNum(), workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 6, 1, sheet.getLastRowNum(), workbook, new Integer[] { 0 });

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 将excel写入流
		workbook.write(byteArrayOutputStream);
		ExcelUtil_Extend.exportExelMerge(response, byteArrayOutputStream, fileName);

		return fileName;
	}

	/**
	 * 日期格式数据绑定
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		sf.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sf, true));
	}

	public static void main(String[] args) {
		Date d  = new Date((long)DateUtil.getStartTimeStamp()*1000);
		System.out.println(d);
	}
}